/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-08-23 17:07:16
 * @LastEditors: cuidm
 * @LastEditTime: 2022-08-24 18:47:31
 * 转移主机到空闲机池
 */
import React, { useState, useEffect, useRef } from "react";
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col, Modal, Tree, Spin, Empty, Radio, Alert } from "antd";
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useModelAssociateType } from "@/components";
import cmdbres from "@/data/cmdbres";
import hcpiam from "@/data/hcpiam";
import request, {requestIAM} from '@/utils/request';
import regexpUtil from "@/utils/regexpUtil";
import hcpUtils from "@/utils/hcpUtils";
import "../index.less";

const user = hcpUtils.getUser();
const BusinessModule = ({ bizInfo, serviceInfo, rowKeys, visible, setVisible, onFinish, cmModuleId}) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [treeData, setTreeData] = useState([]);
    const [dataLoading, setDataLoading] = useState(true);
    const [checkedKeys, setCheckedKeys] = useState([]);
    const [checkedNodes, setCheckedNodes] = useState([]);
    
    const iconName = (code, instanceName) => {
        let name = { biz: "业", set: "集", service: "模" }[code];
        let f = instanceName?.substring(0,1)??'层';
        return  name ? name : f
    }
    
    const dealTopoData = (data) => {//拓扑列表
        data.map(item=> {
            const {instanceId, instanceName, moduleCode, children } = item;
            const obj = {
                key: instanceId,
                title: instanceName,
                icon: <span className="icon">{iconName(moduleCode, instanceName)}</span>,
                checkable: moduleCode == "service" //只允许点击模块
            }
            Object.assign(item, obj);
            if(children) {
                // item.children = child;
                // delete item.child;
                dealTopoData(item.children)
            };
        })

        return data;
    }

    const queryBizTopologyList = async () => {
        try {
            const res = await request({
                ...cmdbres.queryBizTopologyList(bizInfo.bizId),
                data: {},
            });
            if(res && res.data) {
                let arr = [];
                const node = {
                    ...res.data,
                    children: []
                };
                // delete node.child;
                arr.push({
                    ...node,
                    key: node.instanceId,
                    title: node.instanceName,
                    icon: <span className="icon">{iconName(node.moduleCode, node.instanceName)}</span>,
                    checkable: false,
                })
                if(res.data.children) {
                    arr[0].children = dealTopoData(res.data.children);
                }
                setTreeData(arr);
            }
            setDataLoading(false);
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        if(visible && bizInfo) {
            console.log('serviceInfo', serviceInfo);
            queryBizTopologyList();
        }
    }, [visible, bizInfo]);

    const onSubmit = async () => {
        setLoading(true);
        const removeObj = [];
        serviceInfo?.map(info=> {
            info.serviceInstances.map(item=> {
                removeObj.push({
                    serverId: info.server?.cm_unid,//主机ID
                    serviceInstanceId: item.serviceId//模块ID
                })
            })
        });
        let data = {
            author: user.staffName,
            bizId: bizInfo.bizId,
            cmModuleId,
            serverIds: rowKeys,
            addToServices: checkedKeys,
            serviceInstanceOptions: removeObj
        };
        // console.log(data);
        // return;

		let res = await request({
			...cmdbres.moveToService,
			data
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success(`转移主机到业务模块成功！`);
			if (typeof onFinish == "function") onFinish(res);
		}
	};

    const onCancel = () => {
        setVisible(false);
    }

    const onClear = (node) => {
        if(node) {
            let keys = checkedKeys.filter(key=> key != node.key);
            let nodes = checkedNodes.filter(item=> item.key != node.key)
            setCheckedKeys(keys);
            setCheckedNodes(nodes);
        } else {
            setCheckedKeys([]);
            setCheckedNodes([]);
        }
    }

    const onCheck = (checkedKeysValue, e) => {
        setCheckedKeys(checkedKeysValue);
        setCheckedNodes(e.checkedNodes);
    };

    const renderAlert = (node, index) => {
        return (
            <div  className="hcp-alert hcp-alert-info" role="alert" key={index}>
            <span className="hcp-alert-icon icon">{iconName(node.moduleCode, node.instanceName)}</span>
            <div className="hcp-alert-content">
                <div className="hcp-alert-message">{node.instanceName}</div>
                <div className="hcp-alert-description"></div>
            </div>
            <button type="button" className="hcp-alert-close-icon" onClick={()=>{onClear(node)}}>
                <span role="img" aria-label="close" className="anticon anticon-close">
                    <svg
                        viewBox="64 64 896 896"
                        focusable="false"
                        data-icon="close"
                        width="1em"
                        height="1em"
                        fill="currentColor"
                        aria-hidden="true"
                    >
                        <path d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 00203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"></path>
                    </svg>
                </span>
            </button>
            </div>
        )
    }

    return (
        <Modal
            className="hcp-tip-modal hcp-modal-md"
            title="转移主机到业务模块"
            visible={visible}
            onCancel={onCancel}
            footer={null}
            destroyOnClose
            maskClosable={false}
            afterClose={() => {
                form.resetFields();
                setCheckedKeys([]);
                setCheckedNodes([]);
            }}
        >
            <Form
                form={form}
                labelCol={{ span: 5}}
                wrapperCol={{ span: 17 }}
                name="basic"
                onFinish={onSubmit}
            >
                <Row className="box-content">
                    <Col span={12} className="topo-content">
                        <h3 className="title">拓扑列表</h3>
                        {
                            dataLoading ? <Spin /> :
                            treeData.length ?
                            <Tree
                                checkable
                                className="resource-topo-tree"
                                showIcon
                                defaultExpandAll
                                defaultExpandParent
                                treeData={treeData}
                                onCheck={onCheck}
                                checkedKeys={checkedKeys}
                                loading={loading}
                            />
                            :<Empty
                                style={{
                                    border: 'rgb(215,215,215) solid 1px',
                                    width: 500,
                                    padding: '100px 0',
                                }}
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                            />
                        }
                        
                    </Col>
                    <Col span={12} className="preview-content">
                        <h3 className="title">结果预览</h3>
                        <div className="desc">
                            <span>已选择【<span className="num">{checkedKeys.length}</span>】个模块 </span>
                            <span type="primary" onClick={()=>{onClear()}}>清空</span>
                        </div>
                        { checkedNodes.map((node, index)=> {return renderAlert(node, index)})}
                    </Col>
                </Row>
                
                <div className="hcp-modal-body-footer" style={{marginTop: 20}}>
                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button onClick={onCancel} >
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit" loading={loading} disabled={!(checkedKeys && checkedKeys.length)}>
                            提交
                        </Button>
                    </Form.Item>
                </div>
            </Form>
        </Modal>
    );
};

export default BusinessModule;
